package JDBC.socket;

import JDBC.DBUtil;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Server {
    private ServerSocket serverSocket;

    private ExecutorService threadPool = Executors.newFixedThreadPool(50);

//    private List<PrintWriter> allout = new ArrayList<>();
    private Map<String,PrintWriter> allout = new HashMap<>();
    public Server(){
        try {
            System.out.println("服务器启动");
            serverSocket = new ServerSocket(8081);
            System.out.println("服务器启动成功");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void start(){
        try {
            while (true) {
                System.out.println("等待客户端连接...");
                Socket socket = serverSocket.accept();
                System.out.println("一个客户端连接了");

                Runnable clientHandler = new ClientHandler(socket);
                threadPool.execute(clientHandler);
//                Thread t = new Thread(clientHandler);
//                t.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class ClientHandler implements Runnable{
        private Socket socket;
        private String host;
        private String nickname;
        public ClientHandler(Socket socket){
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }
        public void run(){
            PrintWriter pw = null;
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, StandardCharsets.UTF_8);
                BufferedReader br = new BufferedReader(isr);

                nickname = br.readLine();

                OutputStream out = socket.getOutputStream();
                OutputStreamWriter osw = new OutputStreamWriter(out,StandardCharsets.UTF_8);
                BufferedWriter bw = new BufferedWriter(osw);
                pw = new PrintWriter(bw,true);

                synchronized (allout) {
//                    allout.add(pw);
                    allout.put(nickname,pw);
                }
                broadcast(nickname+"["+host+"]"+"上线了,当前在线人数:"+allout.size());

                String massage;
                while((massage=br.readLine())!=null) {
//                    System.out.println(host+"说:"+massage);
//                    for (PrintWriter o : allout) {
//                        o.println(host+"说:"+massage);
//                    }
                    if (massage.startsWith("@")) {
                        sendMessageToSomeone(massage);
                    } else {
                        broadcast(nickname + "[" + host + "]" + "说:" + massage);
                        saveMessage(nickname,null,massage);
                    }
                }
            } catch (IOException e) {
//                e.printStackTrace();
            } finally {
                synchronized (allout) {
//                    allout.remove(pw);
                    allout.remove(nickname);
                }
                broadcast(nickname+"["+host+"]"+"下线了,当前在线人数:"+allout.size());
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        private void broadcast(String message){
            System.out.println(message);
            synchronized (allout) {
                for(PrintWriter o : allout.values()){
                    o.println(message);
                }
            }
        }

        private void sendMessageToSomeone(String message){
            if (message.matches("@.+:.+")) {
                String toNickName = message.substring(1,message.indexOf(":"));
                if(allout.containsKey(toNickName)){
                    PrintWriter pw = allout.get(toNickName);
                    String toMessage = message.substring(message.indexOf(":")+1);
                    pw.println(nickname+"悄悄对你说:"+toMessage);

                    saveMessage(nickname,toNickName,toMessage);

                }else {
                    PrintWriter pw = allout.get(nickname);
                    pw.println("用户不存在");
                }

            }else {
                PrintWriter pw = allout.get(nickname);
                pw.println("私聊格式错误,应当为@对方昵称:私聊消息");
            }
        }

        private void saveMessage(String fromUser,String toUser,String message){
            try (Connection connection = DBUtil.getConnection();){
                String sql="INSERT INTO chatinfo(from_user,to_user,content) " +
                        "VALUES(?,?,?)";
                PreparedStatement ps = connection.prepareStatement(sql);
                ps.setString(1,fromUser);
                ps.setString(2,toUser);
                ps.setString(3,message);
                ps.executeUpdate();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
